<script setup lang="ts">
import { ref, onMounted } from "vue";
import { getPermissionsTree, deletePermission } from "@/api/permission";
import { ElMessage, ElMessageBox } from "element-plus";

const permissions = ref<any[]>([]);
const loading = ref(false);

const fetchPermissions = async () => {
  loading.value = true;
  try {
    const res = await getPermissionsTree();
    if (res.success) {
      permissions.value = res.data;
    } else {
      ElMessage.error(res.message || "获取权限列表失败");
    }
  } catch (error) {
    ElMessage.error("获取权限列表失败");
  } finally {
    loading.value = false;
  }
};

const handleDelete = async (id: number) => {
  ElMessageBox.confirm("确定要删除该权限吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const res = await deletePermission(id);
      if (res.success) {
        ElMessage.success("删除成功");
        fetchPermissions();
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  }).catch(() => {
    // 取消删除
  });
};

onMounted(() => {
  fetchPermissions();
});
</script>

<template>
  <div class="permission-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限列表</span>
          <el-button type="primary" @click="$router.push('/permission/create')">新增权限</el-button>
        </div>
      </template>
      
      <el-table 
        :data="permissions" 
        v-loading="loading" 
        style="width: 100%" 
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="权限名称" />
        <el-table-column prop="code" label="权限代码" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="$router.push(`/permission/edit/${scope.row.id}`)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>